package top.lileix.mybatis.generator.x.kit;

/**
 * 命名工具
 * 
 * @author http://www.oschina.net/code/snippet_870897_19481
 *
 */
public class NamingKit {
    private static final char SEPARATOR = '_';

    /**
     * 驼峰转下划线
     * 
     * @param s
     * @return
     */
    public static String toUnderlineName(String s) {
	if (s == null) {
	    return null;
	}

	StringBuilder sb = new StringBuilder();
	boolean upperCase = false;
	for (int i = 0; i < s.length(); i++) {
	    char c = s.charAt(i);

	    boolean nextUpperCase = true;

	    if (i < (s.length() - 1)) {
		nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
	    }

	    if ((i >= 0) && Character.isUpperCase(c)) {
		if (!upperCase || !nextUpperCase) {
		    if (i > 0)
			sb.append(SEPARATOR);
		}
		upperCase = true;
	    } else {
		upperCase = false;
	    }

	    sb.append(Character.toLowerCase(c));
	}

	return sb.toString();
    }

    /**
     * 驼峰命名
     * 
     * @param s
     * @return
     */
    public static String toCamelCase(String s) {
	if (s == null) {
	    return null;
	}

	s = s.toLowerCase();

	StringBuilder sb = new StringBuilder(s.length());
	boolean upperCase = false;
	for (int i = 0; i < s.length(); i++) {
	    char c = s.charAt(i);

	    if (c == SEPARATOR) {
		upperCase = true;
	    } else if (upperCase) {
		sb.append(Character.toUpperCase(c));
		upperCase = false;
	    } else {
		sb.append(c);
	    }
	}

	return sb.toString();
    }

    /**
     * 首字母大写的驼峰命名
     * 
     * @param s
     * @return
     */
    public static String toCapitalizeCamelCase(String s) {
	if (s == null) {
	    return null;
	}
	s = toCamelCase(s);
	return s.substring(0, 1).toUpperCase() + s.substring(1);
    }

    /**
     * 首字母变小写
     */
    public static String firstCharToLowerCase(String str) {
	char firstChar = str.charAt(0);
	if (firstChar >= 'A' && firstChar <= 'Z') {
	    char[] arr = str.toCharArray();
	    arr[0] += ('a' - 'A');
	    return new String(arr);
	}
	return str;
    }

    /**
     * 首字母变大写
     */
    public static String firstCharToUpperCase(String str) {
	char firstChar = str.charAt(0);
	if (firstChar >= 'a' && firstChar <= 'z') {
	    char[] arr = str.toCharArray();
	    arr[0] -= ('a' - 'A');
	    return new String(arr);
	}
	return str;
    }

}
